package io.rainforest.rss.service.rssmain;

import com.rometools.rome.feed.synd.SyndEntry;
import io.rainforest.rss.client.vo.follow.RssFollowReq;
import io.rainforest.rss.common.util.DateUtil;
import io.rainforest.rss.dao.mapper.RssMainMapperExt;
import io.rainforest.rss.dao.po.RssFollow;
import io.rainforest.rss.dao.po.RssMain;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class RssMainService {

    @Autowired
    RssMainMapperExt rssMainMapperExt;

    public List<RssMain> queryList(String rssId,String title) {
        RssMain rssMain = new RssMain();
        rssMain.setRssId(rssId);
        rssMain.setTitle(title);
        List<RssMain> list = rssMainMapperExt.selectList(rssMain);
        list.forEach(item->{
            // 时间格式转换
            item.setPublishTimeStr(DateUtil.timeStringFromMillions(item.getPublishTime(), "yyyy-MM-dd HH:mm:ss"));
        });
        return list;
    }


    public void addEntryAndCheck(SyndEntry item,String rssId) {
        String uri = item.getLink();
        // 用访问链接做uuid
        String uriMd5 = DigestUtils.md5DigestAsHex(uri.getBytes());
        RssMain rssMain1 = rssMainMapperExt.selectByPrimaryKey(uriMd5);
        if(rssMain1==null){
            RssMain rssMain = new RssMain();
            rssMain.setRssId(rssId);
            rssMain.setUuid(uriMd5);
            rssMain.setLink(uri);
            rssMain.setTitle(item.getTitle());
            Double now = System.currentTimeMillis()+0.0;
            Double publishTime = ObjectUtils.isEmpty(item.getUpdatedDate()) ? now:item.getUpdatedDate().getTime()+0.0;
            rssMain.setPublishTime(publishTime);
            rssMain.setCreateTime(now);
            rssMain.setViewed("0");
            rssMainMapperExt.insertSelective(rssMain);
        }

    }

    public void updateSelective(RssMain main) {
        rssMainMapperExt.updateByPrimaryKeySelective(main);
    }
}